/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.employee.web;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.StoreCardTemplateDuration;
import com.chlitina.store.modules.base.entity.StoreCardTemplateTimes;
import com.chlitina.store.modules.base.entity.StoreCare;
import com.chlitina.store.modules.base.entity.StoreSelfCare;
import com.chlitina.store.modules.base.service.StoreCardTemplateDurationService;
import com.chlitina.store.modules.base.service.StoreCardTemplateTimesService;
import com.chlitina.store.modules.base.service.StoreCareService;
import com.chlitina.store.modules.employee.entity.StoreBonusSettingCare;
import com.chlitina.store.modules.employee.entity.StoreBonusSettingTemplateCare;
import com.chlitina.store.modules.employee.service.StoreBonusSettingTemplateCareService;
import com.chlitina.store.modules.expert.entity.Care;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * 手工护理提成设定模板Controller
 * @author liujiang
 * @version 2013-11-15
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/employee/storeBonusSettingTemplateCare")
public class StoreBonusSettingTemplateCareController extends BaseController {

	@Autowired
	private StoreBonusSettingTemplateCareService storeBonusSettingTemplateCareService;
	@Autowired
	private StoreCardTemplateTimesService storeCardTemplateTimesService;
	@Autowired
	private StoreCardTemplateDurationService storeCardTemplateDurationService;
	@Autowired
	private StoreCareService storeCareService;
	
	@ModelAttribute
	public StoreBonusSettingTemplateCare get(@RequestParam(required=false) Long id) {
		if (id != null){
			return storeBonusSettingTemplateCareService.get(id);
		}else{
			return new StoreBonusSettingTemplateCare();
		}
	}
	
	@RequestMapping(value = "add")
	public String add(int type, StoreBonusSettingTemplateCare storeBonusSettingTemplateCare, Model model) {
		model.addAttribute("storeBonusSettingTemplateCare", storeBonusSettingTemplateCare);
		model.addAttribute("type", type);
		return "modules/employee/storeBonusSettingTemplateCareAdd";
	}
	
	@RequestMapping(value = "addList")
	public String addList(String careIds, int type, StoreBonusSettingTemplateCare storeBonusSettingTemplateCare, Model model, RedirectAttributes redirectAttributes) {
		int bType = storeBonusSettingTemplateCare.getBonus_type();
		float bonus_rate = storeBonusSettingTemplateCare.getBonus_rate()/100;
		float fixed_money = storeBonusSettingTemplateCare.getFixed_money();
		List<Long> saveIds = Lists.newArrayList();
		String [] productList = careIds.split(",");
		for (int i = 0; i < productList.length; i++) {
			String id = productList[i];
			if (StringUtils.isNotEmpty(id)){
				long productId = Long.parseLong(id);
				saveIds.add(productId);
			}
		}
		for (Long id : saveIds) {
			StoreBonusSettingTemplateCare item = new StoreBonusSettingTemplateCare();
			item.setStore(StoreUtils.getStore());
			item.setCard_type(type);
			item.setBonus_type(bType);
			item.setBonus_rate(bonus_rate);
			item.setFixed_money(fixed_money);
			if(type == StoreBonusSettingTemplateCare.CARD_TYPE_TIMES) {
				StoreCardTemplateTimes t = storeCardTemplateTimesService.get(id);
				item.setStoreCare(t.getStoreCare());
			} else if(type == StoreBonusSettingTemplateCare.CARD_TYPE_DURATION){
				StoreCardTemplateDuration t = storeCardTemplateDurationService.get(id);
				item.setStoreCare(t.getStoreCare());
			} else {
				item.setStoreCare(storeCareService.get(id));
			}
			storeBonusSettingTemplateCareService.save(item);
		}
		addMessage(redirectAttributes, "保存手工护理提成设定模板成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingTemplateCare/list?type=" + type;
	}
	
	@RequestMapping(value = {"list", ""})
	public String timesList(@RequestParam(required=false)String currentSelectId, int type, StoreBonusSettingTemplateCare storeBonusSettingTemplateCare, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<StoreBonusSettingTemplateCare> page = storeBonusSettingTemplateCareService.find(new Page<StoreBonusSettingTemplateCare>(request, response), type); 
        model.addAttribute("type", type);
        model.addAttribute("page", page);
        model.addAttribute("currentSelectId", currentSelectId);
        if(type == StoreBonusSettingTemplateCare.CARD_TYPE_TIMES 
        		|| type == StoreBonusSettingTemplateCare.CARD_TYPE_DURATION) {
            model.addAttribute("cardNameMap", getCardNameMap(type, page.getList()));	
        }
		return "modules/employee/storeBonusSettingTemplateCareList";
	}
	
	private Map<Long, String> getCardNameMap(int type, List<StoreBonusSettingTemplateCare> list) {
		Map<Long, String> cardNameMap = Maps.newHashMap();
		for (StoreBonusSettingTemplateCare card : list) {
			Long id = card.getStoreCare().getId();
			if(type == StoreBonusSettingTemplateCare.CARD_TYPE_TIMES) {
				StoreCardTemplateTimes template = storeCardTemplateTimesService.getByCare(id);
				cardNameMap.put(card.getId(), template.getName());
			} else {
				StoreCardTemplateDuration template = storeCardTemplateDurationService.getByCare(id);
				cardNameMap.put(card.getId(), template.getName());
			}
		}
		return cardNameMap;
	}
	
	@RequestMapping(value = "form")
	public String form(int type, StoreBonusSettingTemplateCare storeBonusSettingTemplateCare, Model model) {
		if(type == StoreBonusSettingTemplateCare.CARD_TYPE_TIMES 
        		|| type == StoreBonusSettingTemplateCare.CARD_TYPE_DURATION) {
			StoreCare storeCare = storeBonusSettingTemplateCare.getStoreCare();
			String cardName = "";
			long cardId = 0;
			if(storeCare != null) {
				if(type == StoreBonusSettingTemplateCare.CARD_TYPE_TIMES) {
					StoreCardTemplateTimes template = storeCardTemplateTimesService.getByCare(storeCare.getId());
					cardId = template.getId();
					cardName = template.getName();
				}
				if(type == StoreBonusSettingTemplateCare.CARD_TYPE_DURATION) {
					StoreCardTemplateDuration template = storeCardTemplateDurationService.getByCare(storeCare.getId());
					cardId = template.getId();
					cardName = template.getName();
				}
			}
			model.addAttribute("cardId", cardId);
			model.addAttribute("cardName", cardName);
		}
		model.addAttribute("type", type);
		model.addAttribute("storeBonusSettingTemplateCare", storeBonusSettingTemplateCare);
		return "modules/employee/storeBonusSettingTemplateCareForm";
	}

	@RequestMapping(value = "save")
	public String save(String pageNo, StoreBonusSettingTemplateCare storeBonusSettingTemplateCare, Model model, RedirectAttributes redirectAttributes) {
		storeBonusSettingTemplateCare.setStore(StoreUtils.getStore());
		storeBonusSettingTemplateCare.setBonus_rate(storeBonusSettingTemplateCare.getBonus_rate()/100);
		int type = storeBonusSettingTemplateCare.getCard_type();
		if (!beanValidator(model, storeBonusSettingTemplateCare)){
			return form(type, storeBonusSettingTemplateCare, model);
		}
		storeBonusSettingTemplateCareService.save(storeBonusSettingTemplateCare);
		addMessage(redirectAttributes, "保存手工护理提成设定模板成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingTemplateCare/list?type=" + type+ "&pageNo=" + pageNo +"&currentSelectId=" + storeBonusSettingTemplateCare.getId();
	}
	
	@RequestMapping(value = "delete")
	public String delete(Long id, int type, RedirectAttributes redirectAttributes) {
		storeBonusSettingTemplateCareService.delete(id);
		addMessage(redirectAttributes, "删除手工护理提成设定模板成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingTemplateCare/?type=" + type;
	}
	
	@ResponseBody
	@RequestMapping(value = "timesCardTemplateData")
	public String timesCardTemplateData(HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Set<Map<String, Object>> set = Sets.newHashSet();
		List<Long> existStoreCareId = storeBonusSettingTemplateCareService.getByCardType(StoreBonusSettingTemplateCare.CARD_TYPE_TIMES);
		List<StoreCardTemplateTimes> list = storeCardTemplateTimesService.getByStore();
		for (StoreCardTemplateTimes template : list) {
			Long id = template.getStoreCare().getId();
			if(existStoreCareId.contains(id)) {
				continue;
			}
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", template.getId());
			map.put("name", template.getName());
			set.add(map);
		}
		return JsonMapper.getInstance().toJson(set);
	}
	
	@ResponseBody
	@RequestMapping(value = "durationCardTemplateData")
	public String durationCardTemplateData(HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Set<Map<String, Object>> set = Sets.newHashSet();
		List<Long> existStoreCareId = storeBonusSettingTemplateCareService.getByCardType(StoreBonusSettingTemplateCare.CARD_TYPE_DURATION);
		List<StoreCardTemplateDuration> list = storeCardTemplateDurationService.getByStore();
		for (StoreCardTemplateDuration template : list) {
			Long id = template.getStoreCare().getId();
			if(existStoreCareId.contains(id)) {
				continue;
			}
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", template.getId());
			map.put("name", template.getName());
			set.add(map);
		}
		return JsonMapper.getInstance().toJson(set);
	}

	@ResponseBody
	@RequestMapping(value = "allCardTemplateData")
	public String allCardTemplateData(int type, HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Set<Map<String, Object>> set = Sets.newHashSet();
		List<Long> existStoreCareId = storeBonusSettingTemplateCareService.getByCardType(StoreBonusSettingTemplateCare.CARD_TYPE_All);
		List<StoreCare> careList = storeCareService.findByStatus(type);
		for (StoreCare care : careList) {
			if(existStoreCareId.contains(care.getId())){
				continue;
			}
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", care.getId());
			if(StoreCare.TYPE_SYS == type) {
				if( care.getCare().getStatus() == Care.FLAG_DISABLE){
					continue;
				}
				map.put("name", care.getCare().getName());
			} else {
				if( care.getStoreSelfCare().getStatus() == StoreSelfCare.FLAG_DISABLE){
					continue;
				}
				map.put("name", care.getStoreSelfCare().getName());
			}
			set.add(map);
		}
		return JsonMapper.getInstance().toJson(set);
	}
	
	@ResponseBody
	@RequestMapping(value = "moneyCardTemplateData")
	public String moneyCardTemplateData(int type, HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Set<Map<String, Object>> set = Sets.newHashSet();
		List<Long> existStoreCareId = storeBonusSettingTemplateCareService.getByCardType(StoreBonusSettingTemplateCare.CARD_TYPE_MONEY);
		List<StoreCare> careList = storeCareService.findByStatus(type);
		for (StoreCare care : careList) {
			if(existStoreCareId.contains(care.getId())){
				continue;
			}
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", care.getId());
			if(StoreCare.TYPE_SYS == type) {
				if( care.getCare().getStatus() == Care.FLAG_DISABLE){
					continue;
				}
				map.put("name", care.getCare().getName());
			} else {
				if( care.getStoreSelfCare().getStatus() == StoreSelfCare.FLAG_DISABLE){
					continue;
				}
				map.put("name", care.getStoreSelfCare().getName());
			}
			set.add(map);
		}
		return JsonMapper.getInstance().toJson(set);
	}
}
